home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C05 / NestFriend.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.5 KB  |  89 lines

  1. //: C05:NestFriend.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Nested friends
  7. #include <iostream>
  8. #include <cstring> // memset()
  9. using namespace std;
  10. const int sz = 20;
  11.  
  12. struct Holder {
  13. private:
  14.   int a[sz];
  15. public:
  16.   void initialize();
  17.   struct Pointer {
  18.   private:
  19.     Holder* h;
  20.     int* p;
  21.   public:
  22.     void initialize(Holder* h);
  23.     // Move around in the array:
  24.     void next();
  25.     void previous();
  26.     void top();
  27.     void end();
  28.     // Access values:
  29.     int read();
  30.     void set(int i);
  31.   };
  32.   friend Holder::Pointer;
  33. };
  34.  
  35. void Holder::initialize() {
  36.   memset(a, 0, sz * sizeof(int));
  37. }
  38.  
  39. void Holder::Pointer::initialize(Holder* h) {
  40.   h = h;
  41.   p = h->a;
  42. }
  43.  
  44. void Holder::Pointer::next() {
  45.   if(p < &(h->a[sz - 1])) p++;
  46. }
  47.  
  48. void Holder::Pointer::previous() {
  49.   if(p > &(h->a[0])) p--;
  50. }
  51.  
  52. void Holder::Pointer::top() {
  53.   p = &(h->a[0]);
  54. }
  55.  
  56. void Holder::Pointer::end() {
  57.   p = &(h->a[sz - 1]);
  58. }
  59.  
  60. int Holder::Pointer::read() {
  61.   return *p;
  62. }
  63.  
  64. void Holder::Pointer::set(int i) {
  65.   *p = i;
  66. }
  67.  
  68. int main() {
  69.   Holder h;
  70.   Holder::Pointer hp, hp2;
  71.   int i;
  72.  
  73.   h.initialize();
  74.   hp.initialize(&h);
  75.   hp2.initialize(&h);
  76.   for(i = 0; i < sz; i++) {
  77.     hp.set(i);
  78.     hp.next();
  79.   }
  80.   hp.top();
  81.   hp2.end();
  82.   for(i = 0; i < sz; i++) {
  83.     cout << "hp = " << hp.read()
  84.       << ", hp2 = " << hp2.read() << endl;
  85.     hp.next();
  86.     hp2.previous();
  87.   }
  88. } ///:~
  89.